package service

import (
	"context"
	"encoding/json"
	"ew-srv/basic/config"
	__ "ew-srv/basic/proto"
	"ew-srv/handler/models"
	"fmt"
	"time"
)

type Server struct {
	__.UnimplementedEwServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) GetUserInfo(_ context.Context, in *__.GetUserInfoReq) (*__.GetUserInfoResp, error) {
	var u models.User
	if err := u.GetUserInfo(config.DB, in.Mobile); err != nil {
		return nil, err
	}
	return &__.GetUserInfoResp{
		Id: int64(u.ID),
	}, nil
}
func (s *Server) EClassDetail(_ context.Context, in *__.EClassDetailReq) (*__.EClassDetailResp, error) {
	var u models.Eclass
	if err := u.Geteclass(config.DB, int(in.Id)); err != nil {
		return nil, err
	}
	return &__.EClassDetailResp{
		Title:     u.Title,
		Image:     u.Image,
		Url:       u.Url,
		Price:     float32(u.Price),
		MePrice:   float32(u.MePrice),
		ClassPage: int64(u.ClassPage),
	}, nil
}

func (s *Server) EClassList(_ context.Context, in *__.EClassListReq) (*__.EClassListResp, error) {
	var u models.Eclass
	list, err := u.GeteclassList(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.EClassListResp{
		List: list,
	}, nil
}

func (s *Server) EVideoList(_ context.Context, in *__.EVideoListReq) (*__.EVideoListResp, error) {
	var u models.EVideoass
	list, err := u.GetVideoList(config.DB, int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, err
	}
	return &__.EVideoListResp{
		List: list,
	}, nil
}

func (s *Server) EVideoDetail(_ context.Context, in *__.EVideoDetailReq) (*__.EVideoDetailResp, error) {
	var u models.EVideoass
	if err := u.GetVideo(config.DB, int(in.Id)); err != nil {
		return nil, err
	}
	return &__.EVideoDetailResp{
		Title:    u.Title,
		Image:    u.Image,
		Url:      u.Url,
		TimeLong: u.TimeLong,
		VideoNum: int64(u.VideoNum),
		Status:   int64(u.Status),
	}, nil
}
func (s *Server) EHomeList(_ context.Context, in *__.EHomePageList) (*__.EHomePageListResp, error) {
	var u models.HomePages
	var li []*__.EHomePageList
	key := fmt.Sprintf("%v", u.ID)
	result, _ := config.Rdb.Get(config.Ctx, key).Result()
	if result != "" {
		json.Unmarshal([]byte(key), &result)
	} else {
		masrshl, _ := json.Marshal(&key)
		list, _ := u.GetHomePageList(config.DB)
		config.Rdb.SetNX(config.Ctx, key, masrshl, time.Minute*5)

		fmt.Println(list)
	}
	return &__.EHomePageListResp{
		List: li,
	}, nil
}

func (s *Server) EClassAdd(_ context.Context, in *__.EClassAddReq) (*__.EClassAddResp, error) {
	e := models.Eclass{
		Title:     in.Title,
		Image:     in.Image,
		Url:       in.Url,
		Price:     float64(in.Price),
		MePrice:   float64(in.MePrice),
		ClassPage: int(in.ClassPage),
	}

	if err := e.CreateC(config.DB); err != nil {
		return nil, err
	}

	return &__.EClassAddResp{
		Id: int64(e.ID),
	}, nil
}
